<template>
    <form>
        <slot></slot>
    </form>
</template>

<script>
  export default {
    name: 'iForm',
    props: {
      model: {
        type: Object,
      },
      rules: {
        type: Object
      }
    },
    // 把当前form向下传入，提供给下面的子元素随时拿东西
    provide() {
      return {
        form: this
      }
    },
    data() {
      return {
        fields: [] // 缓存子 formitem
      }
    },
    created() {
      this.$on('on-form-item-add', (field) => {
        if (field) this.fields.push(field)
      })

      this.$on('on-form-item-remove', (field) => {
        if (field) this.fields.splice(this.fields.indexOf(field), 1)
      })
    },
    methods: {
      resetFields() {
        this.fields.forEach(field => {
          field.resetField()
        })
      },

      // 公开方法，全部校验，promise返回
      validate(callback) {
        return new Promise(resolve => {
          let valid = true
          let count = 0
          this.fields.forEach(field => {
            field.validate('', errors => {
              if (errors) {
                valid = false
              }
              if (++count === this.fields.length) {
                resolve(valid)
                if (typeof callback === 'function') {
                  callback(valid)
                }
              }
            })
          })
        })
      }
    }
  }
</script>
